package com.syf.config.result;

import com.syf.config.exception.BizException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import java.util.Date;

/**
 * @desc 全局异常返回结果
 *       备注：该返回信息是spring boot的默认异常时返回结果，目前也是我们服务的默认返回结果
 *
 * @author syf
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class DefaultErrorResult implements Result {

	private static final long serialVersionUID = 1899083570489722793L;

	//HTTP响应状态码 {@link HttpStatus}
	private Integer status;

	//HTTP响应状态码的英文提示
	private String error;

	//异常堆栈的精简信息
	private String message;

	/**
	 * 我们系统内部自定义的返回值编码，{@link ResultCodeEnum} 它是对错误更加详细的编码
	 * 备注：spring boot默认返回异常时，该字段为null
	 */
	private Integer code;

	//调用接口路径
	private String path;

	//异常的名字
	private String exception;

	//异常的错误传递的数据
	private Object errors;

	//时间戳
	private Date timestamp;


	//自定义返回 自定义异常对象(DefaultErrorResult全局异常类，BizException自定义异常枚举信息)
	public static DefaultErrorResult failure(BizException e) {
		//会依次执行一下的所有failure()
		DefaultErrorResult result = DefaultErrorResult.failure(e.getResultCode() == null ? RequestStatusEnum.REQUESR_SUCCESS : e.getResultCode(), e, HttpStatus.OK, e.getData());
		return result;
	}


	//ResultCodeEnum resultCode: 标识所有的异常枚举
	public static DefaultErrorResult failure(ResultCodeEnum resultCode, Throwable e, HttpStatus httpStatus, Object errors) {
		DefaultErrorResult result = DefaultErrorResult.failure(resultCode, e, httpStatus);
		result.setErrors(errors);
		return result;
	}

	public static DefaultErrorResult failure(ResultCodeEnum resultCode, Throwable e, HttpStatus httpStatus) {
		DefaultErrorResult result = new DefaultErrorResult();
		result.setCode(resultCode.getCode());
		result.setMessage(resultCode.getMsg());
		result.setStatus(httpStatus.value());
		result.setError(httpStatus.getReasonPhrase());
		result.setException(e.getClass().getName());
		String path = RequestContextUtil.getRequest().getRequestURI();
		result.setPath(path);
		result.setTimestamp(new Date());
		return result;
	}

}
